package com.vogue.supplymall.shop.common;

import com.vogue.supplymall.common.domain.dto.SearchInfo;
import org.apache.commons.lang3.StringUtils;

/**
 * The type Order utils.
 *
 * @aouthor: zhangliang
 * @date: Create in 2017-12-29
 */
public class OrderUtils {
    /**
     * Order by string.
     * 排序的key 1：销量 2：价格 3：名称 4：评价
     * 排序顺序 1：由低到高 asc 2：由高到低 desc
     *
     * @param searchInfo the search info
     * @param keyName    the key name
     * @return the string
     */
    public static String orderBy(SearchInfo searchInfo, String keyName, Integer replaceKey) {
        if (null == searchInfo) {
            return "";
        }

        if (checkOrder(searchInfo.getOrderKey(), searchInfo.getOrder())) {
            return "";
        }
        StringBuilder order = new StringBuilder().append(" ORDER BY ");
        String result;
        Integer key = 0;
        Integer sort = 0;

        if (searchInfo.getOrderKey().equals(replaceKey)) {
            key = 99;
            sort = searchInfo.getOrder();
        } else {
            key = searchInfo.getOrderKey();
            sort = searchInfo.getOrder();
        }

        result = getOrder(key, sort, keyName);
        if (StringUtils.isEmpty(result)) {
            result = " 1=1 ";
        }
        order.append(result);

        return order.toString();
    }

    public static String orderBy(SearchInfo searchInfo) {
        return orderBy(searchInfo, "",-1);
    }

    /**
     * Order by string.
     * 自定义order by获取
     *
     * @param defaultStr the default str
     * @param field      the field
     * @return the string
     */
    public static String orderBy(String defaultStr, Integer field) {
        if (checkOrder(0, field)) {
            return "";
        }
        String sort = field == 1 ? OrderEnum.ASC.getName() : OrderEnum.DESC.getName();
        return " ORDER BY " + defaultStr + sort;
    }

    private static String getOrder(Integer key, Integer field, String keyName) {
        String sort = field == 1 ? OrderEnum.ASC.getName() : OrderEnum.DESC.getName();
        switch (key) {
            case 1:
                return OrderEnum.sales.getName() + sort;
            case 2:
                return OrderEnum.price.getName() + sort;
            case 3:
                return OrderEnum.sname.getName() + sort;
            case 4:
                return OrderEnum.evaluation.getName() + sort;
            case 99:
                return keyName + sort;
            default:
                return "";
        }
    }

    private static Boolean checkOrder(Integer orderKey, Integer order) {
        return null == orderKey || null == order ? true : false;
    }
}
